
<template>
  <div class="part-batchIn-form">
    <el-table :data="form" :empty-text="$t('part.text22')">
      <el-table-column :label="$t('common.base.name')" width="150px">
        <el-autocomplete
          slot-scope="scope"
          popper-class="batch-in-part"
          v-model="scope.row.sparepartName"
          :fetch-suggestions="fetchSparepart"
          :placeholder="$t('task.tip.addPartTip1')"
          @select="choosePart($event,scope.row)"
        >
          <div class="bacth-in-part-item" slot-scope="scope">
            <p>{{$t('common.base.name')}}：{{scope.item.name}}</p>
            <p>{{$t('common.label.serialNumber')}}：{{scope.item.serialNumber}}</p>
            <p>{{$t('common.part.specifications')}}：{{scope.item.standard}}</p>
            <p v-if="!type && scope.item.description">说明：{{scope.item.description}}</p>
          </div>
        </el-autocomplete>
      </el-table-column>
      <el-table-column :label="$t('common.label.serialNumber')" prop="serialNumber" width="150px" class-name="part-spares-serial-num"></el-table-column>
      <el-table-column :label="$t('common.part.category')" prop="sparepartType"></el-table-column>
      <el-table-column :label="$t('common.label.sparepartStandard')" prop="standard" width="100px"></el-table-column>
      <el-table-column :label="$t('common.base.warehouse')">
        <template slot-scope="scope">
          <span v-if="type">{{scope.row.sparepartName ? scope.row.repertory.name : ''}}</span>
          <el-select v-model="scope.row.repertory" filterable value-key="id" v-else>
            <el-option
              v-for="option in repertory"
              :key="option.id"
              :label="option.name"
              :value="option"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.label.type')">
        <el-select v-model="scope.row.type" slot-scope="scope">
          <el-option
            v-for="option in sparepartConfig.inStoreType"
            :key="option"
            :label="option"
            :value="option"
          ></el-option>
        </el-select>
      </el-table-column>
      <el-table-column :label="$t('common.part.quantity')" width="80px">
        <el-input
          slot-scope="scope"
          v-model="scope.row.variation"
          type="number"
          step="any"
          :min="0"
        ></el-input>
      </el-table-column>
      <el-table-column :label="$t('common.label.operate')" width="60px">
        <el-button type="text" @click="remove(scope.row)" slot-scope="scope">{{ $t('common.base.delete') }}</el-button>
      </el-table-column>
    </el-table>

    <div class="in-stock-remark" v-if="form.length > 0">
      <el-input type='textarea' :maxlength="500" :placeholder="$t('common.base.tip.inputCommentContent')" v-model="remark"></el-input>
    </div>

    <div class="part-batchIn-footer">
      <el-button type="text" @click="add" icon="el-icon-plus">{{ $t('common.paas.buttons.add') }}</el-button>
    </div>
  </div>
</template>

<script>
import MathUtil from "@src/util/math";
import { stringify } from '@src/util/querystring';
import { t } from '@src/locales'

export default {
  name: "part-instockBatch-form",
  inject: ["initData"],
  props: {
    sparepartConfig: Object,
    repertory: Array,
    type: String,
    repertoryName: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      form: [],
      remark: "",
    };
  },
  computed: {
    // TODO: 支持小数 提示
    minVariation() {
      let initData = this.initData;
      return !initData || !initData.precision
        ? 1
        : initData.precision == 1
        ? 0.1
        : 0.01;
    },
    // 默认仓库
    defaultRepertoryId() {
      if (this.form.length) {
        return this.form[this.form.length - 1].repertory.id
      }
      return -1;
    }
  },
  methods: {
    remove(row) {
      let index = -1;
      for (let i = 0; i < this.form.length; i++) {
        if (this.form[i] == row) {
          index = i;
          break;
        }
      }
      if (index >= 0) this.form.splice(index, 1);
    },
    add(event, row = {}) {
      if (this.form.length > 99) {
        return this.$message({
          showClose: true,
          message: t('task.tip.addSparePartTip2', {max:100}),
          type: "error"
        });
      }
      let config = this.sparepartConfig || {};
      let types = config.inStoreType || [];

      let repertories = this.repertory || [];

      let repertory = row.repertory || this.repertoryName;
      let sparepart = row.sparepart || {};
      //默认仓库
      let defaultRepertory = repertories.filter((item => item.id == this.defaultRepertoryId))[0] || repertories[0]
      let id = repertory.id + "_" + sparepart.id;

      if (this.form.length) {
        this.form.push({
          _id: id,
          sparepart: sparepart.id || "",
          sparepartName: sparepart.name || "",
          serialNumber: sparepart.serialNumber || "",
          sparepartType: sparepart.type || "",
          standard: sparepart.standard || "",
          type: this.form[this.form.length - 1].type,
          repertory:
            JSON.stringify(repertory) == "{}" ? defaultRepertory : repertory,
          variation: 1,
        });
        return
      }

      this.form.push({
        _id: id,
        sparepart: sparepart.id || "",
        sparepartName: sparepart.name || "",
        serialNumber: sparepart.serialNumber || "",
        sparepartType: sparepart.type || "",
        standard: sparepart.standard || "",
        type: types[0],
        repertory:
          JSON.stringify(repertory) == "{}" ? defaultRepertory : repertory,
        variation: 1,
      });
    },
    fetchSparepart(keyword, cb) {
      let model = {
        keyWord: keyword,
        pageSize: 50,
        pageNum: 1,
        enable: 1
      };

      this.$http
        .post("/partV2/repertory/sparepart/list", model)
        .then(result => cb(result.list))
        .catch(err => console.log(err));
    },
    hasRow(value) {
      return this.form.some(item => item._id == value);
    },
    choosePart(value, row) {
      let id = row.repertory + "_" + value.id;

      if (this.hasRow(id)) {
        this.$platform.toast(t('common.form.preview.materialVerifyEliminate.tip2'), "warning");
        return;
      }

      row._id = id;
      row.sparepart = value.id;
      row.sparepartName = value.name;
      row.serialNumber = value.serialNumber;
      row.sparepartType = value.type;
      row.standard = value.standard;
    },
    async pack() {
      let form = this.form;
      try {
        let message = "";
        let initData = this.initData;
        form.forEach((item, index) => {
          let count = this.decimalNumber(item.variation);
          if (
            !item.sparepart ||
            !item.repertory.id ||
            !item.type ||
            !item.variation ||
            item.variation <= 0 ||
            count != -1
          ) {
            message = t('part.tips50');
            message +=
              initData.precision == 0
              ? t('common.form.preview.materialOrder.tip6')
              : t('part.tips51', {num:initData.precision});
          }
        });

        if (message) {
          this.$platform.alert(message);
          return null;
        }

        return form.map(item => ({
          sparepart: {
            id: item.sparepart,
            name: item.sparepartName
          },
          repertory: {
            id: item.repertory.id,
            name: item.repertory.name
          },
          item: item.type,
          type: "入库",
          variation: item.variation,
          remark: this.remark
        }));
      } catch (error) {
        console.log(error);
      }
      return null;
    },
    receive(data = []) {
      if (data.length > 20) {
        return this.$platform.alert(t('part.tips59', {num:20}));
      }
      data.forEach(item => this.add(null, item));
    },
    decimalNumber(num) {
      let initData = this.initData;
      let count = MathUtil.decimalNumber(num);
      let isPartV2 = initData.isSparepart2;

      if (!isPartV2 && count != 0) return 0;
      if (initData.precision >= count) return -1;
      return initData.precision;
    }
  }
};
</script>

<style lang="scss">
.el-form-item {
  margin-bottom: 0;
}

.part-batchIn-form {
  td,
  th {
    padding: 5px 0;
  }
  .cell {
    padding: 0 5px;
  }
}

.part-batchIn-footer {
  padding-top: 10px;
  text-align: center;
}

.batch-in-part {
  width: auto !important;
  max-width: 914px !important;
  li {
    padding: 5px;
    margin: 0 10px;
    border-bottom: 1px solid #f0f0f0;
    overflow: hidden;

    &:last-child {
      border-color: transparent;
    }
  }
}

.bacth-in-part-item {
  p {
    width: 100%;
    overflow: hidden;
    white-space: initial;
    text-overflow: ellipsis;
    line-height: 24px;
    margin: 0;
  }
}
.in-stock-remark {
  width: 100%;
  display: flex;
  margin: 10px 0 0;
  padding: 0 5px;
  textarea {
    flex: 1;
    height: 40px;
    min-height: 40px;
    padding: 10px;
    border-color: #dadada;
    &:focus {
      outline: none;
      border-color: $color-primary;
    }
  }
}
</style>